package com.tygz.service.impl;

import java.io.File;
import java.io.InputStream;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.auto.base.pojo.SysAccessory;
import com.auto.base.service.SysAccessoryService;
import com.auto.util.SystemUtil;
import com.base.common.CommonConstants;
import com.base.util.JUtil;
import com.tygz.service.SysAccessoryExtService;

@Transactional
@Service
public class SysAccessoryExtServiceImpl implements SysAccessoryExtService {

	@Resource private SysAccessoryService sysAccessoryService;

	public int upload(SysAccessory record,String relPath,InputStream inputStrram) throws Exception {
		 //如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中  
        //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的 
		if(!JUtil.isNULL(record.getId())){
			SysAccessory queryRecord = new SysAccessory();
			queryRecord.setEnabled(CommonConstants.ENABLE);
			queryRecord.setId(record.getId());
			queryRecord = this.sysAccessoryService.findSysAccessory(queryRecord, null);
			if(!JUtil.isNULL(queryRecord)){
				String filePathPreffix = SystemUtil.getInstance().getParamMap().get("sys_file_save_dir");
				String realPath = getRealPath(queryRecord,filePathPreffix);
				//先删除文件
				File delFile = new File(realPath+"/"+record.getAccessoryName());
				delFile.delete();
				FileUtils.copyInputStreamToFile(inputStrram, new File(relPath, record.getAccessoryName()));  
				int res = this.sysAccessoryService.modifySysAccessoryByPkSelective(record);
				return res;
			}
		}
		FileUtils.copyInputStreamToFile(inputStrram, new File(relPath, record.getAccessoryName()));  
		int res = this.sysAccessoryService.insertSysAccessory(record);  
		return res;
	}
	
	private String getRealPath(SysAccessory record,String sysFileSaveDir){
		String realPath = sysFileSaveDir+"/"+record.getAccessoryClass();
		return realPath;
	}
	
	
}
